package logic

import (
	"context"
	"fmt"
	"mini/pkg"
	"net/http"
	"path/filepath"
	"strings"
	"time"

	"mini/miniapi/internal/svc"
	"mini/miniapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadImageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadImageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadImageLogic {
	return &UploadImageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadImageLogic) UploadImage(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, header, err := req.FormFile("image")
	if err != nil {
		fmt.Println("文件获取失败")
	}
	if header.Size > 5*1024*1024 {
		return &types.Response{
			Message: "文件大小不能超过5mb",
			Code:    500,
			Data:    nil,
		}, nil
	}

	lower := strings.ToLower(filepath.Ext(header.Filename))
	if lower != ".png" && lower != ".jpg" {
		return &types.Response{
			Message: "文件格式只能未png或jpg",
			Code:    500,
			Data:    nil,
		}, nil
	}

	get := req.Form.Get("name")
	filename := "image/" + get + "/" + time.Now().Format("20060102150405") + lower
	yun, err := pkg.QiNiuYun(file, header, filename)
	if err != nil {
		return &types.Response{
			Message: "文件上传失败",
			Code:    500,
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Message: "文件上传成功",
		Code:    200,
		Data:    yun,
	}, nil
}
